# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10148': {
        #  亿鑫支付 支付宝宝到卡扫码 2.8% 10-20000 dwc
        'API_KEY': 'c622976dc51acac1ab7b257dce411933',
        'gateway': 'https://pay.kmzhg.cn/api/sys/addmerchantsorder',
    },
    '10151': {
        #  亿鑫支付 支付宝宝到卡扫码 2.8% 10-20000 zs
        'API_KEY': 'c622976dc51acac1ab7b257dce411933',
        'gateway': 'https://pay.kmzhg.cn/api/sys/addmerchantsorder',
    },
    '10149': {
        #  亿鑫支付 支付宝宝到卡扫码 2.8% 10-20000 witch
        'API_KEY': 'c622976dc51acac1ab7b257dce411933',
        'gateway': 'https://pay.kmzhg.cn/api/sys/addmerchantsorder',
    },
    '10150': {
        #  亿鑫支付 支付宝宝到卡扫码 2.8% 10-20000 loki
        'API_KEY': 'c622976dc51acac1ab7b257dce411933',
        'gateway': 'https://pay.kmzhg.cn/api/sys/addmerchantsorder',
    },
    '10280': {
        #  亿鑫支付 微信扫码 3.5% 50-10000 dwc
        'API_KEY': '4419422bb43bb2363c32a98e98c09d42',
        'gateway': 'https://pay.kmzhg.cn/api/sys/addmerchantsorder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def gen_order_sign(d, key):
    s = 'cpId={}&channel={}&money={}&subject={}&description={}&orderIdCp={}&notifyUrl={}&timestamp={}&ip={}&version={' \
        '}&{}'.format(
        d['cpId'], d['channel'], d['money'], d['subject'], d['description'], d['orderIdCp'], d['notifyUrl'],
        d['timestamp'], d['ip'], d['version'], key
    )
    return generate_sign(s)


def gen_verify_sign(d, key):
    s = 'money={}&orderIdCp={}&version={}&{}'.format(
        d['money'], d['orderIdCp'], d['version'], key
    )
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = gen_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yixinpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay'
    elif service == 'wechat':
        return 'wechat'
    return 'alipay'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('cpId', app_id),
        ('channel', _get_pay_type(service)),
        ('money', str(int(pay_amount * 100))),
        ('subject', 'YiXinPay'),
        ('description', 'charge'),
        ('orderIdCp', str(pay.id)),
        ('notifyUrl', '{}/pay/api/{}/yixinpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('timestamp', int(round(time.time() * 1000))),
        ('ip', _get_device_ip(info)),
        ('version', '1'),
        ('command', 'applyqr'),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("yixinpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['orderIdCp'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("yixinpay data response: %s", response.text)
    return {'charge_info': json.loads(response.text)['data']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("yixinpay notify data: %s, order_id is: %s", data, data['orderIdCp'])
    verify_notify_sign(data, api_key)
    pay_id = data['orderIdCp']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('yixinpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['status']
    trade_no = data['linkId']
    total_fee = float(data['money']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0:成功
    if trade_status == '0':
        _LOGGER.info('yixinpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
